package com.zsy.petshop_01.manager;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zsy.petshop_01.dao.mapper.DiscountMapper;
import com.zsy.petshop_01.model.entity.Discount;
import com.zsy.petshop_01.model.vo.discount.InsertVo;
import com.zsy.petshop_01.model.vo.discount.UpdateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class DiscountManager {
    @Autowired
    DiscountMapper discountMapper;

    public List<Discount> selectAll() {
        return discountMapper.selectList(null);
    }

    public List<Discount> selectByMessage(String message) {
        LambdaUpdateWrapper<Discount> wrapper = new LambdaUpdateWrapper<>();
        wrapper.like(Discount::getMessage, message);
        return discountMapper.selectList(wrapper);
    }

    public void insert(InsertVo insertVo) {
        String startTime = formatTime(Long.valueOf(insertVo.getStartTime()));
        String endTime = formatTime(Long.valueOf(insertVo.getEndTime()));
        String duringTime = startTime + " —— " + endTime;
        Discount discount = new Discount();
        BeanUtils.copyProperties(insertVo, discount);
        discount.setDuringTime(duringTime);
        discountMapper.insert(discount);
    }

    public void update(UpdateVo updateVo) {
        Discount discount = new Discount();
        BeanUtils.copyProperties(updateVo, discount);
        String startTime = formatTime(Long.valueOf(updateVo.getStartTime()));
        String endTime = formatTime(Long.valueOf(updateVo.getEndTime()));
        String duringTime = startTime + " —— " + endTime;
        discount.setDuringTime(duringTime);
        discountMapper.updateById(discount);
    }

    public String formatTime(Long timestamp) {
        Date date = new Date(timestamp);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date);
    }

    public void delete(Integer id) {
        discountMapper.deleteById(id);
    }
}
